# coding: utf-8

from rest_framework import serializers
from album.models import *
from user.models import *
from business.models import *
from material.models import *
from me.exceptions import *
from me.api_utils import JSONSerializerField


class UserBaseInfoSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'avatar', 'nickname', 'gender', )


class AlbumSerializers(serializers.ModelSerializer):
    title = serializers.CharField(max_length=40, required=False, allow_null=True)
    bg_music = JSONSerializerField()
    datas = JSONSerializerField()
    cover = JSONSerializerField()
    create_time = serializers.DateTimeField(format='%Y/%m/%d')
    update_time = serializers.DateTimeField(format='%Y/%m/%d')
    user = UserBaseInfoSerializers(many=False, read_only=True)

    class Meta:
        model = Album
        fields = ('id', 'title', 'bg_music', 'datas', 'cover', 'create_time', 'update_time', 'user')

    def run_validation(self, data):
        datas = data.get('datas', [])
        if datas:
            for item in datas:
                type = item.get('type', None)
                if type not in RESOURCE_TYPES:
                    raise MeException(2002)
                RESOURCE_VALIDATORS[type](item)
        return data

    def update(self, album, validated_data):
        album.title = validated_data.get('title', album.title)
        album.bg_music = validated_data.get('bg_music', album.bg_music)
        album.cover = validated_data.get('cover', album.cover)
        album.is_publish = validated_data.get('is_publish', album.is_publish)
        album.datas = validated_data.get('datas', album.datas)
        album.save()
        return album


class UserSerializers(serializers.ModelSerializer):
    token = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'token', 'avatar', 'nickname', 'gender', )

    def get_token(self, obj):
        return obj.get_token()


class UserWXAppSerializers(UserSerializers):

    def get_token(self, obj):
        return WXAppToken.get_token(obj)


class HelpArticleSerializers(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format='%Y/%m/%d')
    update_time = serializers.DateTimeField(format='%Y/%m/%d')

    class Meta:
        model = HelpArticle
        fields = ('id', 'title', 'content', 'create_time', 'update_time', )


class MusicSerializer(serializers.ModelSerializer):

    class Meta:
        model = Music
        fields = ('id', 'name', 'url')


class MusicGroupSerializer(serializers.ModelSerializer):
    musics = MusicSerializer(source='music_set', many=True)

    class Meta:
        model = MusicGroup
        fields = ('id', 'name', 'musics')

